﻿using RoomMgr.Models;
using RoomMgr.Models.Rooms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RoomMgr.WebApp.Controllers
{
    public class RoomsController : Controller
    {

        EFDataContext context = new EFDataContext();

        public ActionResult Index()
        {
            List<Room> rooms = context.Rooms.ToList();
            return View(rooms);
        }

        public ActionResult Details(int id)
        {
            Room room = context.Rooms.SingleOrDefault(r => r.RoomID == id);
            if (room == null)
            {
                return HttpNotFound();
            }
            return View(room);
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(Room room)
        {
            if (ModelState.IsValid)
            {
                context.Rooms.Add(room);
                context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(room);
        }

        public ActionResult Edit(int id)
        {
            Room room = context.Rooms.Single(r => r.RoomID == id);
            if (room == null)
            {
                return HttpNotFound();
            }
            return View(room);
        }

        [HttpPost]
        public ActionResult Edit(int id, Room room)
        {
            Room _room = context.Rooms.Single(p => p.RoomID == id);

            if (ModelState.IsValid)
            {
                _room.Name = room.Name;
                _room.RoomType = room.RoomType;
                _room.RoomTypeID = room.RoomTypeID;
                _room.DateCreate = room.DateCreate;

                context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(room);
        }

        public ActionResult Delete(int id)
        {
            Room room = context.Rooms.Single(p => p.RoomID == id);
            if (room == null)
            {
                return HttpNotFound();
            }
            return View(room);
        }

        [HttpPost]
        public ActionResult Delete(int id, Room room)
        {
            Room _room = context.Rooms.Single(p => p.RoomID == id);
            context.Rooms.Remove(_room);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            context.Dispose();
            base.Dispose(disposing);
        }
    }
}
